package com.example.itmanager.activity;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.example.itmanager.R;
import com.example.itmanager.api.ApiConfig;
import com.example.itmanager.api.Api_Retrofit;
import com.example.itmanager.entity.LoginResponse;
import com.example.itmanager.util.RetrofitManager;
import com.example.itmanager.util.StringUtils;

import java.net.HttpURLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author 23737
 * 2021.8.9
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener{

    private static final String TAG = "LoginActivity";
    private EditText etAccount;
    private EditText etPwd;
    private EditText etYzm;
    private Button btnLogin;
    private Button btnForPwd;
    private ImageView imgYzm;
    private CheckBox checkBox_rememberMe;

    private int yzmCount = 0;

    private static final String yzmUrl = ApiConfig.BASE_URl+ApiConfig.YZM_LOGIN;

    @Override
    protected int initLayout() {
        return R.layout.activity_login_acitivty;
    }

    @Override
    protected void initView() {
        etAccount = findViewById(R.id.et_account);
        etAccount.requestFocus(); //edittext是一个EditText控件
        popUpKeyBoard(etAccount);
        Log.d(TAG, "initView: ----->"+yzmUrl);

        //对验证码的初始化一定要在刷新/显示验证码之前
        imgYzm = findViewById(R.id.img_yzm);
        RefreshYzm(yzmUrl);

        etPwd = findViewById(R.id.et_pwd);
        etYzm = findViewById(R.id.et_yzm);
        btnLogin = findViewById(R.id.btn_login);
        checkBox_rememberMe = findViewById(R.id.checkbox_remeberme);
        btnForPwd = findViewById(R.id.btn_forgetpwd);
    }


    @Override
    protected void initData() {
        //判断是否有token（是否登录）如果登录直接跳转到主界面，否则进行登录
        if (!StringUtils.isEmpty(findByKey("token"))) {
            navigateTo(HomeActivity.class);
            finish();
        }

        imgYzm.setOnClickListener(this);

        //清楚Glide中的缓存
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(getBaseContext()).clearDiskCache();
            }
        }).start();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Glide.get(getBaseContext()).clearMemory();
            }
        });

       //编写复选框的相关事件
       checkBox_rememberMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
               if (isChecked){
                    yzmCount = 1;
               }else {
                   yzmCount = 0;
               }
           }
       });

       btnLogin.setOnClickListener(this);
       btnForPwd.setOnClickListener(this);
    }

    /*显示验证码*/
    private void RefreshYzm(String s) {
        //使用Picasso图形加载框架
        Glide.with(this)
                .load(s)
                .into(imgYzm);
    }

    //控件的点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_yzm:
                //点击图片，刷新验证码
                RefreshYzm(yzmUrl);
                break;
            case R.id.btn_login:
                String account = etAccount.getText().toString().trim();
                String pwd = etPwd.getText().toString().trim();
                String yzm = etYzm.getText().toString().trim();
                String remMe = String.valueOf(yzmCount);
                login(account,pwd,yzm,remMe);
                break;
            case R.id.btn_forgetpwd:
                break;
        }
    }

    //登录功能的实现
    private void login( String account, String pwd, String yzm,String remMe) {
//        Log.d(TAG, "onClick: --------->"+remMe);
        if (StringUtils.isEmpty(account)) {
            showToast("请输入账号");
            return;
        }
        if (StringUtils.isEmpty(pwd)) {
            showToast("请输入密码");
            return;
        }
        if (StringUtils.isEmpty(yzm)) {
            showToast("请输入验证码");
            return;
        }
        if (StringUtils.isEmpty(remMe)) {
            showToast("请勾选记住我选项");
            return;
        }
        Api_Retrofit api_retrofit = RetrofitManager.getReteofit().create(Api_Retrofit.class);
        Map<String,Object> map = new HashMap<>();
        map.put("username",account);
        map.put("password",pwd);
        map.put("captcha",yzm);
        map.put("rememberMe",remMe);
        Call<LoginResponse> task = api_retrofit.doLogin(map);
        task.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    //获取响应头中的token
                    String token = response.headers().get("token");
                    Log.d(TAG, "token ----- >"+token);
                    insertVal("token",token);
                    showToast("登录成功");
                    navigateToWithFlag(HomeActivity.class,
                            Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                }else {
                    showToast("登录失败");
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t.toString());
            }
        });
    }

    //获取焦点，自动弹出系统软件盘
    public void popUpKeyBoard(EditText editText) {
        Timer timer = new Timer(); //设置定时器
        timer.schedule(new TimerTask() {
            @Override
            public void run() { //弹出软键盘的代码
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editText, InputMethodManager.RESULT_SHOWN);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
            }
        }, 300); //设置300毫秒的时长
    }
}